# -*- coding: utf-8 -*-
from keystoneclient.v2_0 import client as kclient
from keystoneclient.v2_0 import tenants
from keystoneclient.v2_0 import roles
from keystoneclient import session
import httplib2
import keystoneclient
import token
import json
from settings import OPENSTACK_NOVA_VERSION
from settings import OPENSTACK_AUTH_URL
from settings import OPENSTACK_VAL_URL
from settings import OPENSTACK_ADMIN_USER
from settings import OPENSTACK_ADMIN_PASS
from settings import OPENSTACK_ADMIN_TENANT
from novaclient import client as nclient
import time,datetime
from django.http import HttpResponse,HttpResponseRedirect, request
class Keystone():
    
    #login
    def login(self,username,password,tenant_name):
        auth_url = OPENSTACK_AUTH_URL
        v_client=kclient.Client(username=username, password=password, tenant_name=tenant_name, auth_url=auth_url)
        print "[" + username + "] login ok!"
        return v_client
    
    
    def admin_login(self):
        username = OPENSTACK_ADMIN_USER
        password = OPENSTACK_ADMIN_PASS
        project_name = OPENSTACK_ADMIN_TENANT
        auth_url = OPENSTACK_AUTH_URL
        v_client=kclient.Client(username=username, password=password, tenant_name=project_name, auth_url=auth_url)
        print "[" + username + "] login ok!"
        return v_client
        
     #validate token
    def validate(self,token):
       #token = token
       endpoint = OPENSTACK_AUTH_URL
       auth = v2.Token(auth_url=endpoint, token=token)
       sess = session.Session(auth=auth)
       validate_client = kclient.Client(session=sess)
       return validate_client
   
    #create tenants
    def create_tenant(self,v_client,tenant_name,description,enable):
        my_tenant=v_client.tenants.create(tenant_name=tenant_name,description=description, enabled=enable)
        print "create tenant "+my_tenant.name+" success!"
        return  my_tenant
          
     
    #create user and grant role to user  
    def create_user(self,v_client,name,password,tenant,email,enable):
         my_user = v_client.users.create(name=name,password=password,tenant_id=tenant.id,email=email,enabled=enable)
         roles = v_client.roles.list()
         my_role = [x for x in roles if x.name=='user'][0]
         v_client.roles.add_user_role(my_user,my_role,tenant)
         return my_user

     
    #create user and add user to role
    def create_role(self,v_client,role_name):
        role = v_client.roles.create(role_name)
        return role
    
    def create_role(v_client,role_name):
        role = v_client.roles.create(role_name)
        return role
    #delete user 
    def del_user(self,v_client,user_id):
        user = v_client.users.get(user_id)
        user.delete()
        return True
    
    def get_user(self,v_client,user_id):
        user = v_client.users.get(user_id)
        return user
    
    def update_user_state(self,v_client,user_id,enable):
        user = v_client.users.get(user_id)
        v_client.users.update_enabled(user,enable)
        return True
    
    #get a tenant info
    #admin用户获取其他用户tenant信息
    def get_tenant(self,v_client,user_id):
        user = v_client.users.get(user_id)
        tenant = v_client.tenants.get(user.tenantId)
        return tenant
    
    def get_tenant_by_projectId(self,v_client,project_id):
        tenant = v_client.tenants.get(project_id)
        return tenant
    
    def get_tenant_list(self,v_client):
        return v_client.tenants.list()
    
    def get_user_list(self,v_client):
        return v_client.users.list()
    
    def get_servers_list(self,username,password,project_id):
        auth_url = OPENSTACK_AUTH_URL
        version = OPENSTACK_NOVA_VERSION
        novaclient = nclient.Client(version, username, password,project_id,auth_url)
        return novaclient.servers.list()
    
    def get_flavors_list(self,username,password,project_id):
        auth_url = OPENSTACK_AUTH_URL
        version = OPENSTACK_NOVA_VERSION
        novaclient = nclient.Client(version, username, password,project_id,auth_url)
        return novaclient.flavors.list()
    
    
    def getProjectUsage(self,project_id,startTime,endTime):
        
        username = OPENSTACK_ADMIN_USER
        password = OPENSTACK_ADMIN_PASS
        auth_url = OPENSTACK_AUTH_URL
        version = OPENSTACK_NOVA_VERSION
        
        novaclient = nclient.Client(version, username, password,project_id,auth_url)
        
        result = novaclient.usage.get(project_id,startTime,endTime).to_dict()
        
        return result
    
    def judgeUserIn(self,username,password,tenant_name):
        auth_url = OPENSTACK_AUTH_URL
        try:
            v_client=kclient.Client(username=username, password=password, tenant_name=tenant_name, auth_url=auth_url)
            return True
        except:
            return False
    
    def judgeAttrIsexit(self,user,name):
        return hasattr(user, name)
        
    if __name__ == "__main__":
        t_client = admin_login_test()
#         token=t_client.auth_token
#         print token
#         
#         
#        #tt_client=login("admin","admin","admin")
#         
#         #print t_client.service_catalog
#         tt_client= validate(token)
#         print tt_client.users.list()
#         user = tt_client.users.get("169aa499f5ce483981f91e864a686cf4")
#         print user
#        # user.delete()
        
        
      #  keystoneclient.v2_0.tokens.TokenManager.
        #user = get_user(kclient, 'b10ad8bdf96544c0a6c56cc7eed24a8b')
        #print kclient.roles.roles_for_user(user,get_tenant(kclient, 'b10ad8bdf96544c0a6c56cc7eed24a8b'))
        #tenant = create_tenant(kclient,'xiaoyuan','xiaoyuan',True)
        #create_user(kclient,'xiaoyuan','123456',tenant,'xiaoyuan@qq.com',True)
        #print kclient.users.list()
        #print kclient.endpoints.list()
        #print kclient.services.list()
        #print kclient.tenants.get('a375a60cc3f644cf906f337dcb7d4349').list_users()
        #print get_servers_list('admin','ADMIN_PASS','ccb7f95999e3492497f24e8dc2f51b2e')
        #print get_servers_list('liuxiaoming','123456','a375a60cc3f644cf906f337dcb7d4349')
        #kclient = admin_login()
        #tlist = get_tenant_list(kclient)
        #print tlist
        #print len(tlist)
        #v_client=login('admin','ADMIN_PASS','admin')
        #nova = client.Client('2.0', 'yuanzhijin', '123456','9740e3059b8d4e74aed2ae3e025d5536', 'http://controller:5000/v2.0')
        #print nova.flavors.list()
        #print nova.usage.get('9740e3059b8d4e74aed2ae3e025d5536',datetime.datetime.now(),datetime.datetime.now()).to_dict()
        #now = datetime.datetime.now()
        #last_time = now + datetime.timedelta(days=-1)
        #result =  getProjectUsage('ac04c4edaee34ad6b4cc9050ddaee9e1',last_time,now)
        
        #print result
        #print result[u'total_memory_mb_usage']
        #print result[u'total_vcpus_usage']
        #print result[u'total_local_gb_usage']
        
        #for d,x in result.items():
        #    print "key:"+d+",value:"+str(x)
            
        #nova = client.Client('2.0', 'admin', 'ADMIN_PASS','ccb7f95999e3492497f24e8dc2f51b2e', 'http://controller:5000/v2.0')
        #print nova.flavors.list()
        #result = nova.usage.get('ccb7f95999e3492497f24e8dc2f51b2e',datetime.datetime.now(),datetime.datetime.now()).to_dict()
        
        #print result
        
        #for d,x in result.items():
        #    print "key:"+d+",value:"+str(x)
            
        #nova = client.Client('2.0', 'admin', 'ADMIN_PASS','ccb7f95999e3492497f24e8dc2f51b2e', 'http://controller:5000/v2.0')
        #print nova.flavors.list()
        
        #print nova.usage.list(datetime.datetime.now(),datetime.datetime.now())
        #result = nova.usage.get('ccb7f95999e3492497f24e8dc2f51b2e',datetime.datetime.now(),datetime.datetime.now()).to_dict()
        
        
        #loader = loading.get_plugin_loader('password')
        #auth = loader.load_from_options(auth_url='http://controller:5000/v2.0',
        #                        username='yuanzhijin',
        #                        password='123456',
        #                      project_id='9740e3059b8d4e74aed2ae3e025d5536')
        #sess = session.Session(auth=auth)
        #nova = client.Client('2', session=sess)
        #print nova.flavors.list()
        
        #help(nova.manage)
        #tenant=create_tenant(v_client,'6','ddddd',True)
#          create_user(v_client, '2', '111111', tenant , True)
#         create_role(v_client, '22')
#         del_user(v_client,'753e59c14cc24e20b245cce6ccef8378')
        #print v_client.users;
        #validate('admin','ADMIN_PASS','admin')
        #get_tenant(v_client,'0446a32b52ab4e2dbbc3e4bc24eb220f')
        
        
        
        